function(va_alist)
va_dcl
va_list pvar;
va_start(pvar);
f = va_arg(pvar, type);
va_alist is used in a function header to declare a variable argument list.
va_dcl is a declaration for va_alist. No semicolon should follow va_dcl.
va_list is a type defined for the variable used to traverse the list. One such variable must always be declared.
va_start(pvar) is called to initialize pvar to the beginning of the list.
va_arg(pvar, type) will return the next argument in the list pointed to by pvar. type is the type to which the expected argument will be converted when passed as an argument. In standard C, arguments that are char or short are converted to int and should be accessed as int, arguments that are unsigned char or unsigned short are converted to unsigned int and should be accessed as unsigned int, and arguments that are float are converted to double and should be accessed as double. Different types can be mixed, but it is up to the routine to know what type of argument is expected, since it cannot be determined at runtime.
va_end(pvar) is used to finish up.
Multiple traversals, each bracketed by va_start ... va_end, are possible.
va_alist must encompass the entire arguments list. This insures that a #define statement can be used to redefine or expand its value.
The argument list (or its remainder) can be passed to another function using a pointer to a variable of type va_list--- in which case a call to va_arg in the subroutine advances the argument-list pointer with respect to the caller as well.
#include <varargs.h> #define MAXARGS 100 /* execl is called by execl(file, arg1, arg2, ..., (char *)0); */ execl(va_alist) va_dcl { va_list ap; char *file; char *args[MAXARGS]; int argno = 0; va_start(ap); file = va_arg(ap, char *); while ((args[argno++] = va_arg(ap, char *)) != (char *)0) ; va_end(ap); return execv(file, args); }
The macros va_start and va_end may be arbitrarily complex; for example, va_start might contain an opening brace, which is closed by a matching brace in va_end. Thus, they should only be used where they could be placed within a single complex statement.